package com.gzz.demo.multithread.thread;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
  
public class ExecutorServiceDemo {  
  
    public static void testExecute() {  
        ExecutorService executors = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS,  
                new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {  
                    final AtomicInteger threadNumber = new AtomicInteger(1);  
  
                    public Thread newThread(Runnable r) {  
                        Thread t = new Thread(Thread.currentThread().getThreadGroup(), r, "topPatternTasklet-thread"  
                                + (threadNumber.getAndIncrement()));  
                        t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {  
  
                            public void uncaughtException(Thread t, Throwable e) {  
                                System.out.println(e);  
                            }  
                              
                        });  
                        return t;  
                    }  
                }, new ThreadPoolExecutor.CallerRunsPolicy());  
  
        final Random r = new Random();  
        for (int i = 0; i < 10; ++i) {  
            executors.execute(new Runnable() {  
  
                public void run() {  
                    try {  
                        int ri = r.nextInt(1000);  
                        Thread.sleep(ri);  
                        if (ri % 3 == 0) {  
                            System.out.println("ri:" + ri);  
                            throw new RuntimeException("haha error!");  
                        }  
                        System.out.println(Thread.currentThread());  
                    } catch (InterruptedException e) {  
                    }  
                }  
            });  
        }  
  
        executors.shutdown();  
        System.out.println("finished");   
    }  
    public static void main(String[] args) {  
        testExecute();  
    }  
}  
